<template>
  <view class="pay-confirm-container">
    <view class="amount-gradient-card">
      <text class="amount-title">订单金额</text>
      <text class="amount-main">￥{{ amount }}</text>
      <text class="amount-sub">{{ orderInfo }}</text>
    </view>
    <view class="info-card">
      <view class="info-row">
        <text class="info-label">订单信息</text>
        <text class="info-value">{{ orderInfo }}</text>
      </view>
      <view class="info-row">
        <text class="info-label">订单编号</text>
        <text class="info-value">{{ orderNo }}</text>
      </view>
      <view class="info-row">
        <text class="info-label">收款商户</text>
        <text class="info-value">广州云控电子技术有限公司</text>
      </view>
      <!-- 显示费用明细 -->
      <view v-if="orderData.maintenancePrice || orderData.installPrice || orderData.projectPrice" class="fee-details">
        <view class="fee-title">费用明细</view>
        <view v-if="orderData.maintenancePrice && orderData.maintenancePrice > 0" class="fee-row">
          <text class="fee-label">运维费</text>
          <text class="fee-value">¥{{ Number(orderData.maintenancePrice).toFixed(2) }}</text>
        </view>
        <view v-if="orderData.installPrice && orderData.installPrice > 0" class="fee-row">
          <text class="fee-label">安装费</text>
          <text class="fee-value">¥{{ Number(orderData.installPrice).toFixed(2) }}</text>
        </view>
        <view v-if="orderData.projectPrice && orderData.projectPrice > 0" class="fee-row">
          <text class="fee-label">工程费</text>
          <text class="fee-value">¥{{ Number(orderData.projectPrice).toFixed(2) }}</text>
        </view>
      </view>
      <view v-if="payType === 'bank'" class="bank-info-card">
        <text>银行卡号：{{ maskCardNo(orderData.chCardNo) }}</text>
        <text>持卡人姓名：{{ maskName(orderData.chName) }}</text>
        <text>身份证号：{{ maskIdNo(orderData.chIdNo) }}</text>
        <text>手机号：{{ maskMobile(orderData.chMobile) }}</text>
      </view>
    </view>
    <view class="pay-method-card">
      <view class="pay-method-row selected">
        <view class="pay-method-icon">
          <text class="iconfont icon-weixin"></text>
        </view>
        <text class="pay-method-label" v-if="payType === 'wx'">微信支付</text>
        <text class="pay-method-label" v-else>银行卡支付</text>
        <view class="pay-method-checked">
          <text class="iconfont icon-check"></text>
        </view>
      </view>
    </view>
    <view class="pay-btn-fixed">
      <button class="pay-btn" @click="onPay">确认支付 ￥{{ amount }}</button>
      <view class="pay-safe-tip">
        <text class="iconfont icon-lock" style="margin-right:8rpx;"></text>
        <text>平台已加密保护您的支付信息</text>
      </view>
    </view>
  </view>
</template>

<script>
import { submitOrderInfo, singlePay, getOrderStatus, sendServiceMessage, sendMenJinKaTemplate, sendRenLianTemplate, sendYunWeiFeiTemplate } from '@/api/login';
export default {
  data() {
    return {
      orderInfo: '',
      amount: '',
      orderNo: '',
      orderId: '',
      orderData: {},
      payType: '',
      payRes: null,
      pollTimer: null,
      pollCount: 0
    }
  },
  onLoad(options) {
    if (options.data) {
      this.orderData = JSON.parse(decodeURIComponent(options.data));
      if (options.door) {
        this.orderData.door = options.door;
      }
    }
    this.payType = options.payType || 'wx';
    if (options.payRes) {
      this.payRes = JSON.parse(decodeURIComponent(options.payRes));
    }
    if (options.data) {
      // 传递完整订单对象
      try {
        const order = typeof options.data === 'string' ? JSON.parse(options.data) : options.data;
        this.orderData = order;
        // 动态订单信息
        let info = '';
        if (order.type === 2) {
          info = '番禺设备门禁升级缴费';
        } else if (order.type === 3) {
          info = '番禺设备购买门禁卡';
        } else if (order.type === 1) {
          info = '番禺设备运维费';
        } else if (order.type === 4) {
          info = '人脸识别门禁缴费';
        } else {
          info = order.orderInfo || '未知类型';
        }
        this.orderInfo = info;
        // 人脸识别订单(type=3,4)优先使用前端计算的正确总价
        let amount = '0.00';
        if ((order.type === 3 || order.type === 4) && order.correctTotalPrice && Number(order.correctTotalPrice) > 0) {
          // 使用前端传递的正确总价（包含运维费+安装费+工程费）
          amount = (Number(order.correctTotalPrice)).toFixed(2);
        } else if (order.totalPrice && Number(order.totalPrice) > 0) {
          amount = (Number(order.totalPrice)).toFixed(2);
        } else if (order.unitPrice && order.buyCount && Number(order.unitPrice) > 0 && Number(order.buyCount) > 0) {
          amount = (Number(order.unitPrice) * Number(order.buyCount)).toFixed(2);
        }
        this.amount = amount;
        this.orderNo = order.orderNo || '';
        this.orderId = order.id || '';
      } catch (e) {
        this.orderInfo = options.orderInfo || '门禁升级缴费';
        this.amount = options.amount || '0.00';
        this.orderNo = options.orderNo || '';
      }
    } else {
      this.orderInfo = options.orderInfo || '门禁升级缴费';
      this.amount = options.amount || '0.00';
      this.orderNo = options.orderNo || '';
      this.orderId = options.orderId || '';
    }
  },
  methods: {
    maskName(name) {
      if (!name) return '';
      if (name.length === 2) return name[0] + '*';
      if (name.length > 2) return name[0] + '*'.repeat(name.length - 2) + name[name.length - 1];
      return name;
    },
    maskIdNo(id) {
      if (!id || id.length < 8) return id || '';
      return id.substr(0, 4) + '********' + id.substr(-4);
    },
    maskCardNo(cardNo) {
      if (!cardNo || cardNo.length < 8) return cardNo || '';
      return cardNo.substr(0, 4) + ' **** **** ' + cardNo.substr(-4);
    },
    maskMobile(mobile) {
      if (!mobile || mobile.length < 7) return mobile || '';
      return mobile.substr(0, 3) + '****' + mobile.substr(-4);
    },
    failAndBack(title) {
      uni.showToast({ title, icon: 'none' });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    },
    // 根据订单类型获取对应的订阅消息模板ID
    getTemplateId() {
      const templateMap = {
        3: 'XzPc-qsNw8jgNADT9Oj8Q0W3QENIQvHRwLeZHMliDtY', // 人脸识别/门禁升级缴费通知
        2: 'XzPc-qsNw8jgNADT9Oj8Q6UhImiKYPXP-hplBwdJvG4', // 门禁卡购买通知  
        1: 'XzPc-qsNw8jgNADT9Oj8Q2D0lBN6JQJnDHd7tiLkxmU', // 设备运维费缴费通知
        4: 'XzPc-qsNw8jgNADT9Oj8Q0W3QENIQvHRwLeZHMliDtY'  // 人脸识别门禁缴费通知（使用与type3相同的模板）
      };
      return templateMap[this.orderData.type] || null;
    },

    // 发送服务号订阅消息通知（仅支付成功时调用）
    async sendServiceAccountMessage(orderId, orderInfo, amount) {
      const payStatus = '支付成功'; // 支付状态
      const templateId = this.getTemplateId();
      if (!templateId) {
        console.log('当前订单类型无需发送服务号消息');
        return;
      }

      try {
        const openId = uni.getStorageSync('wechat_openid') || '';
        let res;

        // 根据订单类型调用不同的API接口
        if (this.orderData.type === 3) {
          // 门禁卡类型使用专用接口
          let address = this.orderData.address 

          // 从localStorage获取房产详情信息
          try {
            const houseDetailStr = uni.getStorageSync('maintenanceHouseDetail');
            if (houseDetailStr) {
              const houseDetail = JSON.parse(houseDetailStr);
              if (houseDetail.address) address = houseDetail.address;
            }
          } catch (e) {
            console.log('从localStorage获取房产详情失败:', e);
          }

          // 如果还是没有，尝试从maintenanceFormData获取
          if (!address) {
            try {
              const maintenanceFormData = uni.getStorageSync('maintenanceFormData');
              if (maintenanceFormData && maintenanceFormData.addressList && maintenanceFormData.addressList.length > 0) {
                address = maintenanceFormData.addressList[0].fullAddress || '';
              }
            } catch (e) {
              console.log('从maintenanceFormData获取地址失败:', e);
            }
          }

          console.log('门禁卡订单数据:', this.orderData);
          console.log('提取的地址信息:', address);

          const params = {
            openId: openId,
            address: this.orderData.chName, // 地址信息
            phone: this.orderData.phone || this.orderData.chMobile || '', // 手机号
            bishu: this.orderData.buyCount || '1', // 购买数量
            amount: amount
          };
          res = await sendMenJinKaTemplate(params);
          console.log('门禁卡模板消息发送结果:', res);
        } else if (this.orderData.type === 4) {
          // 人脸识别/门禁升级类型使用专用接口
          let address = this.orderData.door 

          // 从localStorage获取房产详情信息
          try {
            const houseDetailStr = uni.getStorageSync('maintenanceHouseDetail');
            if (houseDetailStr) {
              const houseDetail = JSON.parse(houseDetailStr);
              if (houseDetail.address) address = houseDetail.address;
            }
          } catch (e) {
            console.log('从localStorage获取房产详情失败:', e);
          }

          // 如果还是没有，尝试从maintenanceFormData获取
          if (!address) {
            try {
              const maintenanceFormData = uni.getStorageSync('maintenanceFormData');
              if (maintenanceFormData && maintenanceFormData.addressList && maintenanceFormData.addressList.length > 0) {
                address = maintenanceFormData.addressList[0].fullAddress || '';
              }
            } catch (e) {
              console.log('从maintenanceFormData获取地址失败:', e);
            }
          }

          console.log('人脸识别订单数据:', this.orderData);
          console.log('提取的地址信息:', address);

          const params = {
            openId: openId,
            address: address.replace(/\（.*?\）/g, ''), // 地址信息 去掉括号以及括号内的内容 还有可能是中文括号 需要替换
            phone: this.orderData.phone || this.orderData.chMobile || '', // 手机号
            jiaofeixiang: orderInfo, // 缴费项目
            amount: amount,
            payStatus: payStatus // 添加支付状态
          };
          res = await sendRenLianTemplate(params);
          console.log('人脸模板消息发送结果:', res);
        }  else if (this.orderData.type === 1) {
          // 运维费类型使用专用接口
          // 尝试从多个可能的字段获取门禁编码和地址信息
          let mjbm = this.orderData.mjbm || this.orderData.deviceId || this.orderData.deviceCode || this.orderData.doorCode || '';
          let address = this.orderData.door 

          // 从localStorage获取房产详情信息
          try {
            const houseDetailStr = uni.getStorageSync('maintenanceHouseDetail');
            if (houseDetailStr) {
              const houseDetail = JSON.parse(houseDetailStr);
              if (houseDetail.mjbm) mjbm = houseDetail.mjbm;
              if (houseDetail.address) address = houseDetail.address;
            }
          } catch (e) {
            console.log('从localStorage获取房产详情失败:', e);
          }

          // 如果还是没有，尝试从maintenanceFormData获取
          if (!address) {
            try {
              const maintenanceFormData = uni.getStorageSync('maintenanceFormData');
              if (maintenanceFormData && maintenanceFormData.addressList && maintenanceFormData.addressList.length > 0) {
                address = maintenanceFormData.addressList[0].fullAddress || '';
              }
            } catch (e) {
              console.log('从maintenanceFormData获取地址失败:', e);
            }
          }

          console.log('运维费订单数据:', this.orderData);
          console.log('提取的门禁编码:', mjbm);
          console.log('提取的地址信息:', address);

          const params = {
            openId: openId,
            mjbm: mjbm, // 门禁编码
            address: address.replace(/\（.*?\）/g, ''), // 地址信息 去掉括号以及括号内的内容 还有可能是中文括号 需要替换
            phone: this.orderData.phone || this.orderData.chMobile || '', // 手机号
            amount: amount,
            payStatus: payStatus // 添加支付状态
          };
          res = await sendYunWeiFeiTemplate(params);
          console.log('运维费模板消息发送结果:', res);
        } else {
          // 未知类型的订单
          console.log('未知的订单类型:', this.orderData.type);
        }
      } catch (error) {
        console.error('发送服务号订阅消息失败:', error);
      }
    },

    async onPay() {
      // 微信支付
      if (this.payType === 'wx') {
        const openId = uni.getStorageSync('wechat_openid') || '';
        if (!openId) {
          this.failAndBack('未获取到openId');
          return;
        }
        if (!this.orderId || !this.orderNo) {
          this.failAndBack('订单信息缺失');
          return;
        }
        try {
          const res = await submitOrderInfo({ openId, orderId: this.orderId, orderNo: this.orderNo });
          if (res.code === 200 && res.data && res.data && res.data.dataContent) {
            let dataContentObj;
            try {
              dataContentObj = JSON.parse(res.data.dataContent);
            } catch (e) {
              this.failAndBack('支付参数解析失败');
              return;
            }

            if (dataContentObj.resultCode !== 'SUCCESS') {
              this.failAndBack(dataContentObj.errMsg || '交易状态异常，无法支付');
              return;
            }
            if (!dataContentObj.chlRetParam || !dataContentObj.chlRetParam.wc_pay_data) {
              this.failAndBack('缺少支付参数');
              return;
            }

            let wcPayDataObj;
            try {
              wcPayDataObj = JSON.parse(dataContentObj.chlRetParam.wc_pay_data);
            } catch (e) {
              this.failAndBack('支付参数解析失败');
              return;
            }

            const self = this;
            const onWxPay = (payParams) => {
              if (typeof WeixinJSBridge === 'undefined') {
                if (document.addEventListener) {
                  document.addEventListener('WeixinJSBridgeReady', () => onWxPay(payParams), false);
                } else if (document.attachEvent) {
                  document.attachEvent('WeixinJSBridgeReady', () => onWxPay(payParams));
                  document.attachEvent('onWeixinJSBridgeReady', () => onWxPay(payParams));
                }
                return;
              }
              WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                appId: payParams.appId,
                timeStamp: payParams.timeStamp,
                nonceStr: payParams.nonceStr,
                package: payParams.package,
                signType: payParams.signType,
                paySign: payParams.paySign
              },
                (bridgeRes) => {
                  if (bridgeRes.err_msg === 'get_brand_wcpay_request:ok') {
                    uni.showToast({ title: '支付成功', icon: 'success' });
                    self.pollCount = 0;
                    self.pollOrderStatus(self.orderId);

                    // 支付成功后发送服务号订阅消息
                    self.sendServiceAccountMessage(self.orderId, self.orderInfo, self.amount);

                    // 跳转到商家小票页面（如果没有点金计划，这段代码会执行）
                    setTimeout(() => {
                      uni.redirectTo({
                        url: `/pages/common/goldplan/index?orderNo=${self.orderNo}&amount=${self.amount}&orderInfo=${encodeURIComponent(self.orderInfo)}&orderId=${self.orderId}`
                      });
                    }, 1500);
                  } else {
                    let errMsg = '支付失败';
                    if (bridgeRes.err_msg && bridgeRes.err_msg.indexOf(':cancel') > -1) {
                      errMsg = '支付已取消';
                    }
                    self.failAndBack(errMsg);
                  }
                }
              );
            }
            onWxPay(wcPayDataObj);
          } else {
            this.failAndBack(res.msg || '支付失败');
          }
        } catch (e) {
          this.failAndBack('支付异常');
        }
      } else {
        // 银行卡支付
        // 显示确认弹窗
        uni.showModal({
          title: '支付确认',
          content: `您将使用尾号${this.orderData.chCardNo ? this.orderData.chCardNo.substr(-4) : ''}的银行卡支付¥${this.amount}，确认支付吗？`,
          confirmText: '确认支付',
          confirmColor: '#07c160',
          cancelText: '取消',
          success: async (res) => {
            if (res.confirm) {
              // 用户点击确认，继续支付流程
              uni.showLoading({ title: '处理中...' });
              try {
                const params = {
                  amount: this.amount * 100,
                  chCardNo: this.orderData.chCardNo,
                  chIdNo: this.orderData.chIdNo,
                  chMobile: this.orderData.chMobile,
                  chName: this.orderData.chName,
                  email: this.orderData.email || '',
                  idCard: this.orderData.idCard || '',
                  identifyState: this.orderData.identifyState || '',
                  nickName: this.orderData.nickName || '',
                  orderNo: this.orderData.orderNo,
                  payIp: this.orderData.payIp || '',
                  phone: this.orderData.phone || '',
                  protocolNo: this.orderData.protocolNo || '',
                  registerIp: this.orderData.registerIp || '',
                  registerTime: this.orderData.registerTime || '',
                  userId: this.orderData.userId || '',
                  userName: this.orderData.userName || ''
                };
                const res = await singlePay(params);
                uni.hideLoading();
                if (res.code === 200) {
                  uni.showToast({ title: '银行卡支付成功', icon: 'success' });
                  // 银行卡支付成功后也可轮询
                  this.pollCount = 0;
                  this.pollOrderStatus(this.orderId);

                  // 支付成功后发送服务号订阅消息
                  this.sendServiceAccountMessage(this.orderId, this.orderInfo, this.amount);

                  // 跳转到商家小票页面
                  setTimeout(() => {
                    uni.redirectTo({
                      url: `/pages/common/goldplan/index?orderNo=${this.orderNo}&amount=${this.amount}&orderInfo=${encodeURIComponent(this.orderInfo)}&orderId=${this.orderId}`
                    });
                  }, 1500);
                } else {
                  uni.showToast({ title: res.msg || '银行卡支付失败', icon: 'none' });
                }
              } catch (e) {
                uni.hideLoading();
                uni.showToast({ title: '银行卡支付异常', icon: 'none' });
              }
            }
          }
        });
      }
    },
    pollOrderStatus(orderId) {
      if (this.pollTimer) clearTimeout(this.pollTimer);
      this.pollCount++;
      getOrderStatus(orderId)
        .then(res => {
          if (res.data && res.data.data && res.data.data.status === '已付款') {
            uni.showToast({ title: '付款成功', icon: 'success' });
            // 可跳转到订单详情页
            // uni.redirectTo({ url: `/pages/mine/payment/detail?orderId=${orderId}` });
          } else if (this.pollCount < 30) {
            this.pollTimer = setTimeout(() => this.pollOrderStatus(orderId), 3000);
          } else {
            uni.showToast({ title: '支付结果超时，请稍后在订单中查看', icon: 'none' });
          }
        })
        .catch(() => {
          if (this.pollCount < 30) {
            this.pollTimer = setTimeout(() => this.pollOrderStatus(orderId), 3000);
          } else {
            uni.showToast({ title: '支付结果超时，请稍后在订单中查看', icon: 'none' });
          }
        });
    },
    onUnload() {
      if (this.pollTimer) clearTimeout(this.pollTimer);
    }
  }
}
</script>

<style lang="scss" scoped>
.pay-confirm-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 180rpx;
}

.amount-gradient-card {
  margin: 0rpx 24rpx 0 24rpx;
  padding: 56rpx 0 36rpx 0;
  background: linear-gradient(90deg, #07c160 0%, #34d399 100%);
  border-radius: 48rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 8rpx 32rpx rgba(7, 193, 96, 0.10);

  .amount-title {
    color: #fff;
    font-size: 30rpx;
    opacity: 0.85;
    margin-bottom: 18rpx;
    letter-spacing: 2rpx;
  }

  .amount-main {
    color: #fff;
    font-size: 80rpx;
    font-weight: bold;
    margin-bottom: 12rpx;
    letter-spacing: 2rpx;
    text-shadow: 0 2rpx 8rpx rgba(7, 193, 96, 0.10);
  }

  .amount-sub {
    color: #fff;
    font-size: 28rpx;
    opacity: 0.85;
    margin-top: 6rpx;
    letter-spacing: 1rpx;
  }
}

.info-card {
  background: #fff;
  border-radius: 32rpx;
  margin: -24rpx 24rpx 32rpx 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
  padding: 36rpx 32rpx 18rpx 32rpx;
}

.info-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 30rpx;
  margin-bottom: 18rpx;

  .info-label {
    color: #888;
    font-size: 28rpx;
  }

  .info-value {
    color: #222;
    font-weight: 500;
    font-size: 30rpx;
    word-break: break-all;
    text-align: right;
  }
}

.fee-details {
  margin-top: 24rpx;
  padding-top: 24rpx;
  border-top: 1rpx solid #f0f0f0;

  .fee-title {
    color: #333;
    font-size: 30rpx;
    font-weight: 600;
    margin-bottom: 16rpx;
  }

  .fee-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12rpx;

    .fee-label {
      color: #666;
      font-size: 28rpx;
    }

    .fee-value {
      color: #333;
      font-weight: 500;
      font-size: 28rpx;
    }
  }
}

.pay-method-card {
  background: #fff;
  border-radius: 32rpx;
  margin: 0 24rpx 0 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
  padding: 18rpx 24rpx 18rpx 24rpx;
}

.pay-method-row {
  display: flex;
  align-items: center;
  width: 100%;
  border: 2rpx solid transparent;
  border-radius: 24rpx;
  padding: 18rpx 0;
  margin-bottom: 0;
  transition: border 0.2s;

  &.selected {
    border: 2rpx solid #07c160;
    background: #eafaf3;
  }

  .pay-method-icon {
    color: #07c160;
    font-size: 56rpx;
    margin-right: 22rpx;
  }

  .pay-method-label {
    font-size: 34rpx;
    color: #222;
    flex: 1;
    font-weight: bold;
    letter-spacing: 1rpx;
  }

  .pay-method-checked {
    color: #07c160;
    font-size: 44rpx;
  }
}

.pay-btn-fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  box-shadow: 0 -2rpx 16rpx rgba(7, 193, 96, 0.06);
  padding: 32rpx 0 18rpx 0;
  z-index: 99;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pay-btn {
  width: 92%;
  background: linear-gradient(90deg, #07c160 0%, #34d399 100%);
  color: #fff;
  font-size: 40rpx;
  border-radius: 56rpx;
  height: 108rpx;
  line-height: 108rpx;
  font-weight: bold;
  box-shadow: 0 4rpx 16rpx rgba(7, 193, 96, 0.10);
  letter-spacing: 2rpx;
  border: none;
  margin-bottom: 18rpx;
}

.pay-safe-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #aaa;
  font-size: 24rpx;
  margin-top: 0;
}

.bank-info-card {
  background: #f7f7f7;
  border-radius: 12px;
  padding: 32rpx;
  margin: 32rpx 0;
  font-size: 30rpx;
  color: #333;
  display: flex;
  flex-direction: column;
  gap: 18rpx;
}
</style>